#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author : bird.zhang@ximalaya.com

try:
    import xml.etree.cElementTree as ElementTree
except ImportError:
    import xml.etree.ElementTree as ElementTree

print '==========================  example 1  ============================'

sample_xml_path = './sample.xml'

tree = ElementTree.parse(sample_xml_path)

root = tree.getroot()

print 'scm/locations/hudson.scm.SubversionSCM_-ModuleLocation/remote :'
print root.findall('scm/locations/hudson.scm.SubversionSCM_-ModuleLocation/remote')

# 打印一个标签的四个属性
print type(root.tag)
print type(root.attrib)
print type(root.text)
print type(root.tail)

# 寻找一个子标签
children = root.getchildren()

for child in children:
    print child.tag

print '==========================  example 2  ============================'

xml_str = """
<a>
    <b>1</b>
    <b>2</b>
    <c>
        <d>
            <b>3</b>
            <b>4</b>
        </d>
        <e>
            <b>5</b>
            <b>6</b>
        </e>
    </c>
</a>
"""

print 'ElementTree.fromstring()返回的类型是：'
print type(ElementTree.fromstring(xml_str))

root = ElementTree.fromstring(xml_str)

print 'iter()'
nodes = root.iter('b')
print nodes

print 'root.tag=' + root.tag

nodes = root.findall("a")  # 自己是搜索不到
print len(nodes)

nodes = root.findall("*")  # 找打text为1，2的b和C
print nodes

nodes = root.findall('.//b')
for node in nodes:
    print node.text

nodes = root.findall('c/d')
print nodes

nodes = root.findall('c/d/b')
print nodes

nodes = root.findall('*/b')
print '*/b'
print nodes

nodes = root.findall('*/d')
print '*/d'
print nodes

nodes = root.findall('*/*/b')
print '三级子元素中b标签的个数', len(nodes)

print '==========================  example 3  ============================'
print '增加节点'

xml_str = '''
<a>
</a>
'''

root = ElementTree.fromstring(xml_str)

# 打印节点
print ElementTree.tostring(root)

print '==========================  example 4  ============================'
print '删除节点'

xml_str = '''
<a>
    <b>1</b>
    <b>2</b>
    <c>
        <d>
            <b>3</b>
            <b>4</b>
        </d>
        <e>
            <b>5</b>
            <b>6</b>
        </e>
    </c>
</a>
'''

root = ElementTree.fromstring(xml_str)

nodes = root.findall('c')

for node in nodes:
    root.remove(node)

print '删除后的xml：'
print ElementTree.tostring(root)
ElementTree.dump(root)

print 'str(root)', str(root)

print '==========================  example 5  ============================'
print '修改节点'
